package com.study.selection.controller;

import com.study.selection.model.Student;
import com.study.selection.model.Teacher;
import com.study.selection.service.StudentService;
import com.study.selection.service.TeacherService;
import com.study.selection.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    TeacherService teacherService;
    @Autowired
    StudentService studentService;

    @RequestMapping("/login")
    public String doLogin(int username, String password, int role, Model model,HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        if (role == 1) { //如果是学生
            //根据登录学生的Id查询对应学生
            Student student = studentService.getByStudentId(username);
            //判断查询到的学生对象是否为空且密码是否相等
            if (student!=null&&student.getPassword().equals(MD5Utils.getMD5(password))){
                //创建session学生对象
                session.setAttribute("student",student);
                return "/view/Student/index.jsp";
            }else {
                //查询不到
                if(student==null){
                    model.addAttribute("result","该账号不存在!");
                    return "/loginagain.jsp";
                }else {
                    //密码不匹配
                    model.addAttribute("result","密码错误!");
                    return "/loginagain.jsp";
                }
            }
        }
        if (role == 2) { //如果是教师
            //根据登录教师的Id查询对应教师
            Teacher teacher = teacherService.getByTeacherId(username);
            //判断查询到的教师对象是否为空且密码是否相等
            if (teacher!=null && teacher.getPassword().equals(MD5Utils.getMD5(password))){
                session.setAttribute("teacher",teacher);
                return "/view/teacher/index.jsp";
            }else {
                if(teacher==null){
                    model.addAttribute("result","该账号不存在!");
                    return "/loginagain.jsp";
                }else {
                    model.addAttribute("result","密码错误!");
                    return "/loginagain.jsp";
                }
            }

        }
        if (role == 3) { //如果是管理员
            //判断用户名和密码是否匹配
            if(username==99999&&password.equals("admin")){
                return "/view/admin/index.jsp";
            }else {
                //不匹配直接提示登录失败，不提示是用户名不存在还是密码错误
                    model.addAttribute("result","登录失败!");
                    return "/loginagain.jsp";
            }
        }
        return null;
    }

}
